<template>
	<a-modal
		:visible="visible"
		width="1000px"
		title="退租"
		centered
		destroyOnClose
		:maskClosable="false"
		@cancel="cancel"
		:footer="null"
		:bodyStyle="{padding: 0}">
		<a-form
			ref="formRef"
			:model="modelRef"
			:rules="formRules"
			layout="horizontal"
			class="flex-container-nomal"
			:labelCol="{style: {width: '120px'}}"
			style="height: 70vh"
			@finish="submit">
			<div class="flex1 auto-y">
				<a-space :size="12" direction="vertical" style="width: 100%">
					<div class="d-module-title">
						<b>房间信息</b>
					</div>
					<a-form-item label="" name="houseAddress">
						<a-input v-model:value="modelRef.houseAddress" disabled placeholder="请输入房源地址" />
					</a-form-item>

					<div class="d-module-title">
						<b>退租情况</b>
						<span
							v-if="
								baseNumbe.eleMaterStatusName == '离线' &&
								baseNumbe.clodWaterMaterStatusName !== '离线' &&
								baseNumbe.hotWaterMaterStatusName !== '离线'
							"
							class="error-color">
							(电表已离线，请确认好电费已结清后再进行退租)
						</span>
						<span
							v-else-if="
								baseNumbe.eleMaterStatusName !== '离线' &&
								[baseNumbe.clodWaterMaterStatusName, baseNumbe.hotWaterMaterStatusName].includes('离线')
							"
							class="error-color">
							(水表已离线，请确认好水费已结清后再进行退租)
						</span>
						<span
							v-else-if="
								baseNumbe.eleMaterStatusName == '离线' &&
								[baseNumbe.clodWaterMaterStatusName, baseNumbe.hotWaterMaterStatusName].includes('离线')
							"
							class="error-color">
							(水电表已离线，请确认好水电费已结清后再进行退租)
						</span>
					</div>
					<a-row :gutter="10" style="height: 35px">
						<a-col>
							<a-form-item label="" name="normal">
								<a-radio-group
									v-model:value="modelRef.normal"
									button-style="solid"
									:disabled="isResubmit"
									@change="onNoramlChange">
									<a-radio-button :value="1">到期退</a-radio-button>
									<a-radio-button :value="2">违约退</a-radio-button>
									<a-radio-button :value="3">协议退</a-radio-button>
								</a-radio-group>
							</a-form-item>
						</a-col>
						<a-col>
							<a-form-item label="合同退租日期" name="endTime">
								<a-date-picker v-model:value="modelRef.endTime" :value-format="DATE_FORMAT.DATE" disabled />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="10" style="height: 35px">
						<a-col>
							<a-form-item label="实际退租日期" name="quiteDate" :rules="[{required: true, message: '请选择实际退租日期'}]">
								<a-date-picker
									v-model:value="modelRef.quiteDate"
									:value-format="DATE_FORMAT.DATE"
									:disabled="(contractDetail.contractStatus == 23 || isResubmit) && ![1, 2, 3].includes(modelRef.normal)"
									:disabled-date="disabledDate"
									@change="incomeList()" />
							</a-form-item>
						</a-col>
						<a-col>
							<a-form-item label="退款账号" name="paymentAccount">
								<a-input-group compact>
									<a-form-item-rest>
										<a-select
											v-model:value="modelRef.paymentAccountType"
											:options="paymentAccountList"
											placeholder="请选择类型"
											style="width: 80px" />
									</a-form-item-rest>
									<a-input style="width: 200px" v-model:value="modelRef.paymentAccount" placeholder="请输入账号" />
								</a-input-group>
							</a-form-item>
						</a-col>

						<!-- 重新提交不展示退房交割单 结算也不展示-->
						<a-col v-if="!isResubmit && rentingOutType !== 'settlement'">
							<a-button v-show="showDelivery()" type="primary" @click="addClick" style="width: 160px">
								<check-outlined v-if="JSON.stringify(delivery.info) != '{}' && delivery.info" />
								<plus-outlined v-else />
								确认退房交割单
							</a-button>
						</a-col>
					</a-row>

					<a-row :gutter="30" v-if="[1].includes(modelRef.paymentAccountType)">
						<a-col>
							<a-form-item :labelCol="{style: {width: '70px'}}" labelAlign="left" label="银行行号" name="bankNumber">
								<a-input style="width: 325px" v-model:value="modelRef.bankNumber" placeholder="请输入银行行号" />
							</a-form-item>
						</a-col>
						<a-col>
							<a-form-item :labelCol="{style: {width: '70px'}}" labelAlign="left" label="开户银行" name="bankName">
								<a-input style="width: 279px" v-model:value="modelRef.bankName" placeholder="请输入开户银行" />
							</a-form-item>
						</a-col>
					</a-row>

					<div class="d-module-title">
						<b>退租明细</b>
					</div>
					<vxe-grid v-bind="gridOptions" :data="tableData" align="center">
						<template #feeDirection="{row}">
							<svg-icon
								:icon-class="`finance-${row.feeDirection == 1 ? 'in' : 'out'}`"
								style="width: 22px; height: 14px; margin-right: 6px" />
							<span :class="(row.feeDirection == 1 ? 'processing' : 'error') + '-color'">
								{{ row.feeDirection == 1 ? '收' : '支' }}
							</span>
						</template>
						<template #feeSubject="{row}">
							<a-select
								v-model:value="row.feeSubjectId"
								:class="{error: !row.feeSubjectId}"
								:disabled="row.disabled"
								:options="row.isNew ? useFeeSubject : feeSubject"
								show-search
								option-filter-prop="name"
								:field-names="{label: 'name', value: 'id', options: 'metaList'}"
								placeholder="请选择费用科目"
								style="width: 100%; text-align: left" />
						</template>
						<template #amount="{row}">
							<a-input-number
								v-model:value="row.notOccurredMoney"
								:class="{error: row.notOccurredMoney === null || row.notOccurredMoney < 0}"
								:min="0"
								:precision="2"
								placeholder="请输入金额"
								style="width: 100%" />
						</template>
						<template #cycle="{row}">
							<a-range-picker
								:class="{error: !row.timeInfo.length}"
								style="width: 100%"
								v-model:value="row.timeInfo"
								:value-format="DATE_FORMAT.DATE" />
						</template>
						<template #action="{row, rowIndex}">
							<a-button type="link" size="small" danger @click="tableData.splice(rowIndex, 1)">删除</a-button>
						</template>
						<template #bottom>
							<vxe-toolbar perfect>
								<template #buttons>
									<span>费用总计：{{ totalMoney.toLocaleString() }}元</span>
								</template>
								<template #tools>
									<!-- v-if="!(props.bizId && [1, '1'].includes(props.enterpriseSignType))" -->
									<a-space>
										<a class="processing" @click="addTogether(1)">
											<plus-square-outlined />
											添加收款项
										</a>
										<a class="error" @click="addTogether(2)">
											<minus-square-outlined />
											添加付款项
										</a>
									</a-space>
								</template>
							</vxe-toolbar>
						</template>
					</vxe-grid>

					<div class="d-module-title">
						<b>备注</b>
					</div>
					<a-form-item label="" name="quiteComment">
						<a-textarea v-model:value="modelRef.quiteComment" placeholder="请输入备注" :rows="4" show-count :maxlength="200" />
					</a-form-item>
				</a-space>
			</div>
			<div class="a-modal-dialog-footer">
				<a-space :size="12">
					<a-button @click="cancel">取消</a-button>
					<template v-if="canDeduct">
						<a-button :loading="loading" :disabled="loading" type="primary"
								  @click="submit(false)">退租，不抵扣账单
						</a-button>
						<a-button :loading="loading" :disabled="loading" type="primary"
								  @click="submit(true)">保存，并抵扣账单
						</a-button>
					</template>
					<a-button v-else :loading="loading" :disabled="loading" type="primary"
							  @click="submit(false)">确定
					</a-button>
				</a-space>
			</div>
		</a-form>
		<device-tip v-model:visible="deviceTipVisible" :accessShow="accessShow" :lockShow="lockShow" @success="handleOk"></device-tip>

		<lease-off-settlement
			v-model:visible="deliveryVisible"
			:id="props.contractId"
			:houseId="modelRef.houseId"
			:is-resubmit="isResubmit"
			@success="getDelivery"
			:getDelivery="XEUtils.clone(delivery.info, true)"></lease-off-settlement>

		<generate-bill v-model:visible="visibles.generateBill" :data="[]" :inpude-show="[]" />

		<!-- 账单抵扣 -->
		<bill-deductionVue
			v-model:visible="billDeduction"
			:enterPriseContractId="props.enterPriseContractId"
			:totalMoney="Number(totalMoney)"
			:id="props.contractId"
			:data="tableData"
			:modelRef="modelRef"
			:rentingOutType="rentingOutType"
			@cancel="close"></bill-deductionVue>
	</a-modal>
</template>
<script setup lang="ts">
	import {computed, reactive, ref, watch} from 'vue'
	import {
		cabcelBreakAbnormalList,
		getCurEleAndWaterQuantity,
		getRenterContractDetail,
		houseDeliverySave,
		deviceStatus,
		tenantBreakAbNormal,
		tenantBreakNormal,
		tenantBreakNormalList,
		break_agreement,
		break_settle,
		break_agreement_list
	} from '@/api/contract'
	import {paymentAccountList} from '@/utils'
	import {MinusSquareOutlined, PlusOutlined, PlusSquareOutlined, CheckOutlined} from '@ant-design/icons-vue'
	import dayjs, {Dayjs} from 'dayjs'
	import {useRequest} from 'vue-request'
	import {message, Modal} from 'ant-design-vue'
	import LeaseOffSettlement from './lease-off-settlements.vue'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'
	import {RenterContract} from '@/interface/contract'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {DIC_LABEL_MAP} from 'yuxin-base/src/constant'
	import DeviceTip from '@/components/contract/tenant/device-tip.vue'
	import GenerateBill from '@/components/finance/generate-bill/index.vue'
	import BillDeductionVue from '@/components/contract/contract-detail-dialog/charter-contract/bill-deduction.vue'
	import {isD3B} from 'yuxin-base/src/utils/device'
	import {isLockinEnv} from 'yuxin-base/src/utils'
	import {VxeGridProps, VxeTablePropTypes} from 'vxe-table'
	import {getHouseDeliveryGetNoe} from '@/api/contract'
	import XEUtils from 'xe-utils'
	import {addFinanceAndDetail} from '@/api/bill'

	const props = defineProps({
		visible: {
			type: Boolean,
			required: true
		},
		contractId: {
			type: String,
			default: ''
		},
		applyId: {
			type: [String, Number],
			default: ''
		},
		quiteDate: {
			type: [String],
			default: ''
		},
		enterPriseContractId: {
			type: [String],
			default: null
		},
		isResubmit: {
			type: Boolean,
			required: false
		},
		isShow: {
			type: Boolean,
			default: false
		},
		enterpriseSignType: {
			type: [String],
			default: null
		},
		bizId: {
			type: [String],
			default: ''
		},
		rentingOutType: {
			type: [String],
			required: false,
			default: ''
		}
	})

	const lockInfo = ref<any>({})
	const deliveryVisible = ref<boolean>(false)
	const deviceTipVisible = ref<boolean>(false)
	// const houseId = ref<boolean>(false)
	const modelRef = reactive({
		quiteDate: '',
		quiteComment: '',
		houseId: '',
		// 只作展示用的字段
		houseAddress: '',
		normal: 2,
		paymentAccountType: 1,
		paymentAccount: '',
		endTime: '',
		bankNumber: null,
		bankName: null
	})
	const visibles = reactive({
		generateBill: false
	})
	const formRules = {}

	const deliveryId = ref<any>('')

	const feeSubject = ref<any>([])
	const useFeeSubject = ref<any>([])
	const billDeduction = ref<boolean>(false)
	const disabledDate = (current: Dayjs) => {
		return false
		// 非合同即将搬入状态只能选择合同开始日期到当天日期
		// const validateBegineTime = dayjs(current).format('YYYY-MM-DD') < dayjs(contractDetail.value.beginTime).format('YYYY-MM-DD')
		// const validate = validateBegineTime || dayjs(current).format('YYYY-MM-DD') > dayjs().format('YYYY-MM-DD')
		// return modelRef.normal === 3 ? validateBegineTime : validate
		// return current && current.isAfter(dayjs().add(1, 'day'), 'day')
	}

	const addClick = () => {
		deliveryVisible.value = true
		console.log(modelRef.houseId, 'modelRef.houseIdmodelRef.houseId')
	}

	const contractDetail = ref<RenterContract>({})

	const getData = () => {
		// 获取租客详情
		getRenterContractDetail(props.contractId).then(({data}) => {
			console.log('查询租客合同详情', data.cancelInfo)
			contractDetail.value = data
			modelRef.houseAddress = data.house.address
			modelRef.endTime = data.endTime

			modelRef.houseId = data.houseId
			let date = new Date()
			let beginTime = new Date(data.beginTime)
			let quiteDate = ''
			if (props.quiteDate) {
				quiteDate = props.quiteDate
			} else {
				if (date.getTime() < beginTime.getTime()) {
					modelRef.quiteDate = nowDate()
					// quiteDate = dayjs(contractDetail.value.contractStatus == 23 ? new Date().getTime() : beginTime).format(DATE_FORMAT.DATE)
				} else {
					quiteDate = nowDate()
				}

				// 结算 使用实际退租日期
				if (props.rentingOutType === 'settlement') {
					quiteDate = data.quiteDate
				}
			}

			modelRef.quiteDate = quiteDate
			const sameDate = dayjs().format('YYYY-MM-DD') === dayjs(data.endTime).format('YYYY-MM-DD')

			if (data.contractStatus == 31) {
				modelRef.normal = 1
				// modelRef.quiteDate = data.endTime
			}

			if (!props.isResubmit) {
				sameDate && (modelRef.normal = 1)
				incomeList()
			} else {
				let billInfos = (data.billInfos || []).filter(o => o.num == 999) || [],
					bills = billInfos.length ? (billInfos[0]?.bills || []).filter(k => k.billType == 3) : [],
					finances = bills.length ? bills[0].finances : []
				billProcessing(finances)
			}
			// 获取水电表 云丁环境 结算不调用
			if (isLockinEnv() && props.rentingOutType !== 'settlement') {
				setEleAndWaterQuantity()
			}
			modelRef.bankName = data?.cancelInfo?.bankName
			modelRef.bankNumber = data?.cancelInfo?.bankNumber
			modelRef.paymentAccount = data.cancelInfo?.paymentAccount
		})
		// 获取费用科目列表
		// 82308字典修改
		settingApi.getDicListByLabel(DIC_LABEL_MAP.FEESUBJECT, {isUse: null}).then(({data}) => {
			data.forEach((item: any) => {
				item.selectable = false
			})
			feeSubject.value = data
		})

		// 82308字典修改
		settingApi.getDicListByLabel(DIC_LABEL_MAP.FEESUBJECT, {isUse: 1}).then(({data}) => {
			data.forEach((item: any) => {
				item.selectable = false
			})
			useFeeSubject.value = data
		})
	}
	const lockShow = ref<boolean>(false)
	const accessShow = ref<boolean>(false)

	//获取门禁门锁是否离线
	const getDeviceInformation = () => {
		deviceStatus(props.contractId).then((res: any) => {
			let data = res.data
			if (data?.hasLock && !data.lockOnline) {
				lockShow.value = true
			}
			if (data?.hasAccess && !data.accessOnline) {
				accessShow.value = true
			}
			if (accessShow.value || lockShow.value) {
				deviceTipVisible.value = true
			} else {
				message.success('操作成功')
				emit('success')
				cancel()
			}
		})
	}
	const handleOk = () => {
		deviceTipVisible.value = false
		emit('success')
		cancel()
	}
	const baseNumbe = ref<any>({})
	const setEleAndWaterQuantity = () => {
		// 获取水电表详情
		getCurEleAndWaterQuantity({
			roomId: modelRef.houseId
		}).then((res: any) => {
			baseNumbe.value = res.data
		})
	}

	const onNoramlChange = () => {
		if (modelRef.normal === 1) {
			modelRef.quiteDate = nowDate()
			// modelRef.quiteDate = contractDetail.value?.endTime || nowDate()
		} else {
			modelRef.quiteDate = nowDate()
		}
		incomeList()
	}

	const incomeList = async (data: any = []) => {
		const params = {
			contractId: props.contractId,
			quiteDate: modelRef.quiteDate,
			meterReadRecordDtos: data
		}
		const apiMap = {
			2: cabcelBreakAbnormalList,
			1: tenantBreakNormalList,
			3: break_agreement_list
		}
		const res: any = await apiMap[modelRef.normal](params)
		billProcessing(res.data)
	}
	const billProcessing = data => {
		data.forEach((item: any) => {
			item.disabled = true
			item.timeInfo = [item.beginDate, item.endDate]
			// 表单校验
			item.checkFeeSubjectId = true
			item.checkAmount = true
			item.checkTimeInfo = true
		})
		tableData.value = data
		billListInfo()
	}
	const billList = async (data: any = []) => {
		data.forEach((item: any) => {
			item.disabled = true
			item.timeInfo = [item.beginDate, item.endDate]
			// 表单校验
			item.checkFeeSubjectId = true
			item.checkAmount = true
			item.checkTimeInfo = true
			let index = tableData.value.findIndex(o => o.id === item.id)
			if (index === -1) {
				tableData.value.push(item)
			} else {
				tableData.value[index] = {...item}
			}
		})

		filterTableData()
	}

	const totalMoney = computed(() => {
		let total = 0
		for (let item of tableData.value) {
			if (item.feeDirection === 1) {
				total += item.notOccurredMoney * 1
			} else {
				total -= item.notOccurredMoney * 1
			}
		}
		return total.toFixed(2)
	})

	const canDeduct = computed(() => {
		// 只有企业合同可以抵扣
		if (!props.enterPriseContractId) return false
		// 需要总费用小于0
		if (Number(totalMoney.value) >= 0) return false
		return true
	})

	// table ---------------------------------------------------------------------------------------------------------

	const gridOptions = reactive<VxeGridProps>({
		size: 'small',
		maxHeight: 400,
		rowConfig: {
			isHover: true,
			isCurrent: true
		},
		columns: [
			{
				title: '收支类型',
				field: 'feeDirection',
				width: 100,
				align: 'center',
				slots: {
					default: 'feeDirection'
				}
			},
			{
				title: '费用科目',
				field: 'feeSubjectId',
				minWidth: 200,
				align: 'center',
				slots: {
					default: 'feeSubject'
				}
			},
			{
				title: '费用承担方',
				width: 150,
				align: 'center',
				visible: !!contractDetail.value.enterPriseId,
				formatter() {
					return '企业承担'
				}
			},
			{
				title: '金额(元)',
				field: 'amount',
				minWidth: 150,
				align: 'center',
				slots: {
					default: 'amount'
				}
			},
			{
				title: '账单周期',
				field: 'cycle',
				align: 'center',
				minWidth: 300,
				slots: {
					default: 'cycle'
				}
			},
			{
				title: '操作',
				align: 'center',
				width: 100,
				slots: {
					default: 'action'
				}
			}
		]
	})

	const tableData = ref<any>([])
	const deliveryNote = ref<any>({})

	const addTogether = (type: number | string) => {
		let obj = {
			// 收支金额
			amount: null,
			timeInfo: [],
			beginDate: '',
			// 费用类型
			costType: 0,
			endDate: '',
			// 费用方向【1收入2支出】
			feeDirection: type,
			// 费用科目id【字典】
			feeSubjectId: null,
			// 费用科目名称
			feeSubjectName: '',
			// 表单校验
			checkFeeSubjectId: true,
			checkAmount: true,
			checkTimeInfo: true,
			notOccurredMoney: null,
			isNew: true
		}
		tableData.value.push(obj)
	}
	watch(
		() => props.visible,
		async (newVal: boolean) => {
			console.log(props.bizId, '88', props.enterpriseSignType, '00')
			if (newVal) {
				getData()
				if (isLockinEnv()) {
					const {data = {}} = await deviceStatus(props.contractId)
					lockInfo.value = data
				}
				if (props.bizId) {
					getDeliveryF()
				}
			} else {
				baseNumbe.value = {}
			}
		}
	)
	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		emit('update:visible', false)
		resetForm()
	}

	const delivery = reactive<any>({
		info: {}
	})
	const isCheckDelivery = ref(false)
	const getDelivery = (data: any) => {
		delivery.info = data
		isCheckDelivery.value = true
		// 设备费用存在 刷新账单
		if (delivery.info?.meterReadRecordDtos && delivery.info.meterReadRecordDtos.length) {
			Modal.warning({
				title: '提示',
				content: '账单已更新，还请重新核对账单明细!'
			})
			incomeList(delivery.info.meterReadRecordDtos)
		} else {
			billListInfo()
		}
	}
	const billListInfo = () => {
		if (delivery.info?.earlyData && delivery.info.earlyData.length) {
			billList(delivery.info.earlyData)
		}
		// 能源预警
		if (delivery.info?.energyDictArr && delivery.info.energyDictArr.length) {
			billList(delivery.info.energyDictArr)
		}

		filterTableData()
	}

	const submit = async (deduct: boolean) => {
		filterTableData()

		// 82308字典修改
		if (await isDisabledF()) return

		if (!props.enterPriseContractId) {
			if (modelRef.normal === 1 && dayjs().isBefore(modelRef.quiteDate, 'day')) {
				return message.error('合同未到期，无法办理到期退')
			}

			// isBindEnergyDevice 是否绑定能耗设备 0.是 1.否 结算跳过
			if (props.rentingOutType === '') {
				if (contractDetail.value.isBindEnergyDevice === 0 && JSON.stringify(delivery.info) === '{}') {
					if (!isLockinEnv()) return message.error('请在交割单输入能耗读数')
				}
			}

			if (isLockinEnv()) {
				handleOfflineLock()
			}

			let checkFee = false

			checkFee = amountHandler((checkFee = false))
			if (checkFee) {
				return
			}

			run()
		} else {
			if (canDeduct.value) {
				// 如果是重新提交的数据就跳过退房交割单的校验 结算不校验
				if (!isCheckDelivery.value && !props.isResubmit && props.rentingOutType === '') {
					message.error('请先确认退房交割单')
					return
				}
			}
			let checkFee = false
			amountHandler((checkFee = false))
			if (!deduct) {
				sendRequest()
				cancel()
				setTimeout(() => {
					emit('success')
				}, 200)
			} else {
				deliverySave(props.contractId)
				modelRef['deliveryAddForm'] = XEUtils.clone(deliveryNote.value, true)
				// 退租的时候需要删除id 不然会导致物业交割单被更新为空数据
				if (modelRef['deliveryAddForm']?.id) delete modelRef['deliveryAddForm'].id
				// 退租提交不提交物业交割单
				if (props.isResubmit && modelRef['deliveryAddForm']) delete modelRef['deliveryAddForm']
				// 结算不提交
				if (props.rentingOutType === 'settlement') delete modelRef['deliveryAddForm']
				billDeduction.value = true
			}
		}
	}

	const sendRequest = () => {
		deliverySave(props.contractId)
		if (props.bizId) {
			deliveryNote.value.id = deliveryId.value
		}

		const params: any = {
			backType: modelRef.normal,
			contractId: props.contractId,
			houseId: modelRef.houseId,
			finances: tableData.value,
			quiteComment: modelRef.quiteComment,
			quiteDate: modelRef.quiteDate,
			paymentAccountType: modelRef.paymentAccountType,
			paymentAccount: modelRef.paymentAccount,
			bankNumber: modelRef.bankNumber,
			bankName: modelRef.bankName,
			deliveryAddForm: XEUtils.clone(deliveryNote.value, true),
			isBreakNotCalc: props.rentingOutType === 'settlement' ? true : false
			// deliveryAddForm: delivery.info
		}
		if (props.applyId !== '') {
			params.applyId = props.applyId
		}
		// 退租的时候需要删除id 不然会导致物业交割单被更新为空数据
		if (params.deliveryAddForm.id) delete params.deliveryAddForm.id
		// 退租提交不提交物业交割单
		if (props.isResubmit && params.deliveryAddForm) delete params.deliveryAddForm
		const apiMap = {
			2: tenantBreakAbNormal,
			1: tenantBreakNormal,
			3: break_agreement
		}
		// 结算
		if (props.rentingOutType === 'settlement') return break_settle(params)

		return apiMap[modelRef.normal](params)
	}

	const {run, loading} = useRequest(sendRequest, {
		manual: true,
		formatResult: (res: any) => {
			if (res.code == 200) {
				//提交物业交割单
				// deliverySave(props.contractId)
				if (isLockinEnv()) {
					getDeviceInformation()
				} else {
					close()
				}
			}
		}
	})

	const deliverySave = (contractId: string) => {
		// 过滤字段 deviceType,deviceId,amount or lastRead=》read
		// 深拷贝一下 防止污染
		let newDelivery = JSON.parse(JSON.stringify(delivery.info))
		// 根据付费类型 不同的数组
		// let type = newDelivery.billGenerateMethod
		// if (type === 2 || type === 3) {
		// 	meters = newDelivery[type === 2 ? 'meterReadRecordDtos' : 'energyDictArr'].map((e: any) => {
		// 		return {
		// 			deviceType: e.deviceType,
		// 			deviceId: e.deviceId,
		// 			read: type === 2 ? e.amount : e.lastRead
		// 		}
		// 	})
		// 	delete newDelivery['meterReadRecordDtos']
		// 	delete newDelivery['energyDictArr']
		// }
		let meterReadRecordDtos = []
		if (newDelivery && newDelivery.constructor === Object && newDelivery.hasOwnProperty('meterReadRecordDtos')) {
			meterReadRecordDtos =
				(newDelivery.meterReadRecordDtos || []).map((e: any) => {
					return {
						deviceType: e.deviceType,
						deviceId: e.deviceId,
						read: e.amount
					}
				}) || []
			delete newDelivery['meterReadRecordDtos']
		}
		let energyDictArr = []
		if (newDelivery && newDelivery.constructor === Object && newDelivery.hasOwnProperty('energyDictArr')) {
			energyDictArr =
				(newDelivery.energyDictArr || []).map((e: any) => {
					return {
						deviceType: e.deviceType,
						deviceId: e.deviceId,
						read: e.lastRead
					}
				}) || []
			delete newDelivery['energyDictArr']
		}
		let meters = [...meterReadRecordDtos, ...energyDictArr]
		//需要查一遍签约成功的合同
		deliveryNote.value = {
			deliveryType: '2',
			compactType: '1',
			houseId: modelRef.houseId,
			compactId: contractId,
			meters,
			...newDelivery
		}
		// houseDeliverySave(data).finally(() => {
		// 	if (!isLockinEnv()) {
		// 		close()
		// 	}
		// })
	}

	// 重置表单
	const formRef = ref<any>()
	const resetForm = () => {
		modelRef.houseId = ''
		modelRef.paymentAccountType = 1
		tableData.value = []
		delivery.info = {}
		formRef.value.resetFields()
	}
	const close = () => {
		cancel()
		emit('success')
	}

	/**
	 * 过滤账单金额为0的项
	 */
	const filterTableData = () => {
		tableData.value = tableData.value.filter((item: any) => {
			return item.notOccurredMoney !== 0
		})
	}

	const handleOfflineLock = () => {
		const {hasLock, sn} = lockInfo.value || {}
		if (hasLock && isD3B(sn)) {
			Modal.warning({
				title: '提醒',
				icon: null,
				content: '请使用管家端锁前连接蓝牙后删除门锁授权。或设备详情中获取删除码门前按键输入删除码后删除。'
			})
			// 无需返回
			// return true
		}
		// return false
	}

	const showDelivery = () => {
		let temp = true
		if (props.isShow) {
			temp = false
		}
		// 包租合同单个退租展示退租交割单
		if ([1, '1'].includes(props.enterpriseSignType)) {
			temp = true
		}
		return temp
	}

	// 获取退房交割单
	const getDeliveryF = () => {
		let params = {
			id: props.bizId,
			type: 2
		}
		getHouseDeliveryGetNoe(params).then((res: any) => {
			delivery.info = res.data || {}
			if (res.data) {
				deliveryId.value = res?.data.id
			}
		})
	}

	const amountHandler = checkFee => {
		for (let item of tableData.value) {
			item.checkFeeSubjectId = !item.feeSubjectId ? false : true
			if (!item.feeSubjectId) {
				checkFee = true
			}
			item.checkAmount = item.notOccurredMoney * 1 >= 0
			if (item.notOccurredMoney === null || !(item.notOccurredMoney * 1 >= 0)) {
				checkFee = true
			}
			if (item.timeInfo.length == 0) {
				item.checkTimeInfo = false
				checkFee = true
			} else {
				item.beginDate = item.timeInfo[0]
				item.endDate = item.timeInfo[1]
				item.checkTimeInfo = true
			}

			// 总金额=未发生金额+已发生金额
			item.amount = item.notOccurredMoney + (item.occurredMoney || 0)
		}
		return checkFee
	}

	/* 判断选择的字典是否被禁用 */
	// / 82308字典修改
	const isDisabledF = async () => {
		let temp = false
		let typesList: any = []
		let list: any = []
		typesList = await settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: 1})
		typesList.data.forEach((e: any) => {
			list.push(...e.metaList)
		})
		list.forEach((e: any) => {
			tableData.value.forEach((o: any) => {
				if (e.id === o.feeSubjectId) {
					o.active = true
				}
			})
		})
		if (!tableData.value?.every((e: any) => e?.active == true)) {
			temp = true
			return message.error('选项已禁用，请选择其他选项！')
		}
		return temp
	}
</script>

<style lang="less" scoped>
	:deep(.vxe-table--footer-wrapper.body--wrapper) {
		overflow: hidden;
	}
</style>
